package main

import (
	"config"
	"fmt"
	"github.com/cihub/seelog"
	"github.com/go-redis/redis"
	"public"
	"sync"
	"syscall"
	"time"
)

var logger seelog.LoggerInterface
var wg sync.WaitGroup //定义一个同步等待的组
var num int
var tasks chan uint64
var rdsCli *redis.Client

func GenerateTask(cycle int) {
	for i := 0; i < cycle; i++ {
		tasks <- public.RandomImei()
		num++
	}
}

func Run(cycle int) {
	defer wg.Done()
	var exitFlag bool
	for !exitFlag {
		select {
		case imei := <-tasks:
			newImei := public.ImeiToImei(cycle, imei)
			key := fmt.Sprintf("%d", newImei)
			rdsCli.Set(key, imei, 0)
			logger.Infof("%s %d", key, imei)
		case <-time.After(100 * time.Second):
			exitFlag = true
			break
		}
	}
}

func setLogger() (err error) {
	logxml := `<seelog>
    <outputs formatid="runtime">
        <buffered formatid="runtime" size="10000" flushperiod="100">
            <rollingfile type="date" filename="./log/runtime.log" datepattern="2006-01-02-15" maxrolls="240"/>
        </buffered>
    </outputs>
    <formats>
        <format id="runtime" format="%Date %Time:	%Msg%n"/>
    </formats>
</seelog>`
	logger, err = seelog.LoggerFromConfigAsBytes([]byte(logxml))
	return err
}

func watch() {
	for {
		time.Sleep(time.Minute)
		logger.Infof("run current cycle num[%d]", num)
	}
}

func main() {

	cfg, err := config.Init("./conf/conf.json")
	if err != nil {
		fmt.Println(err.Error())
		syscall.Exit(-1)
	}

	err = setLogger()
	if err != nil {
		fmt.Printf("setLogger error[%s]\n", err.Error())
		syscall.Exit(-1)
	}

	address := fmt.Sprintf("%s:%d", cfg.RdsHost, cfg.RdsPort)
	fmt.Println(address)
	rdsCli = redis.NewClient(&redis.Options{
		Addr:     address,
		Password: cfg.RdsPassword,
		DB:       cfg.RdsDb,
	})

	tasks = make(chan uint64, 10000)
	num = 0

	go GenerateTask(cfg.Cycles)
	go watch()

	funcCycles := 3000000000000 / cfg.Cycles
	for i := 0; i < cfg.Rountines; i++ {
		go Run(funcCycles)
		logger.Infof("start run %d groutine", i)
		wg.Add(1)
	}
	wg.Wait()
	logger.Info("main exit")
	rdsCli.Close()
	close(tasks)
}
